import fs from 'fs';
import { fromMarkdown } from 'mdast-util-from-markdown';
import { translate } from 'bing-translate-api';

const markdown = fs.readFileSync('./CHANGELOG.md', 'utf-8');

const extractText = node => node.children?.map(child => child.value).join('') || '';

const parseListItem = async listItem => {
  let itemDetails = { title_en: '', title_ch: '', desc: [], url: '', link: '', author: '' };

  for (const part of listItem.children) {
    if (part.type === 'paragraph') {
      for (const element of part.children) {
        switch (element.type) {
          case 'text':
            itemDetails.title_en += element.value;
            itemDetails.title_ch += await translationFn(element.value);
            break;
          case 'link':
            itemDetails.link = element.url;
            itemDetails.author = extractText(element).replace(/\[|\]/g, '');
            break;
          case 'image':
            itemDetails.url = element.url;
            break;
        }
      }
    } else if (part.type === 'list') {
      let result = await Promise.all(
        part.children.map(async descItem => {
          let tempDescItem = extractText(descItem.children[0]);
          return tempDescItem
            ? translationFn(tempDescItem).then(title_ch => ({
                title_en: tempDescItem,
                title_ch,
              }))
            : null;
        })
      );
        console.log('result --->', result);
      itemDetails.desc = result;
    }
  }

  // 返回最终的 itemDetails 对象
  return itemDetails;
};

const parseList = async listNode => {
  const listItems = listNode.children.map(parseListItem);
  return await Promise.all(listItems);
};
const parseMarkdown = async markdown => {
  const ast = fromMarkdown(markdown);
  let versions = [];

  const promises = ast.children.map(async (node, index) => {
    if (node.type === 'heading' && node.depth === 2) {
      const versionInfo = node.children[0].value.match(/V\d+\.\d+\.\d+ \(\d{4}\.\d+\.\d+\)/);
      if (versionInfo) {
        const [version, time] = versionInfo[0].split(' (');
        versions.push({
          version: version.trim(),
          time: time.replace(')', '').trim(),
          fns: [],
        });
      }
    } else if (node.type === 'heading' && node.depth === 3 && versions.length > 0) {
      const title_en = node.children[0].value;
      const title_ch = await translationFn(node.children[0].value);
      const nextNode = ast.children[index + 1];
      const lists = nextNode && nextNode.type === 'list' ? await parseList(nextNode) : [];
      versions[versions.length - 1].fns.push({ title_en, title_ch, lists });
    }
  });
  await Promise.allSettled(promises); // 等待所有翻译完成
  return versions;
};

const translationFn = async text => {
  // console.log('text ---->', text);
  if (!text) return text;
  try {
    const result = await translate(text, null, 'zh-Hans');
    // console.log('result ---->', result);
    return (result && result?.translation) || text;
  } catch (error) {
    // console.error('翻译错误:', error);
    return text;
  }
};

const main = async () => {
  const versions = await parseMarkdown(markdown);
  fs.writeFileSync('./translation.json', JSON.stringify(versions, null, 2), (err, res) => {
    if (err) {
      console.error(err);
    } else {
      console.log('文件写入成功');
      process.exit();
    }
  });
};

main().catch(console.error);
